<template>
  <div class="chat-container">
    <!-- Sidebar for desktop -->
    <div class="sidebar" :class="{ 'hidden': !showSidebar, 'collapsed': sidebarCollapsed && showSidebar }">
      <!-- 折叠状态下的垂直布局 -->
      <div v-if="sidebarCollapsed" class="collapsed-layout">
        <!-- Logo 占位 -->
        <div class="collapsed-item logo-container">
          <img src="/logo.png" alt="Logo" class="sidebar-logo" />
        </div>

        <!-- 展开按钮占位 -->
        <div class="collapsed-item">
          <button @click="toggleCollapse" class="sidebar-action-btn" title="展开侧边栏">
            <Icon icon="mdi:chevron-right-box-outline" width="28" height="28" />
          </button>
        </div>

        <!-- 新建会话按钮占位 -->
        <div class="collapsed-item">
          <button @click="createNewConversation" class="sidebar-action-btn" title="新建会话">
            <Icon icon="mdi:content-save-edit" width="28" height="28" />
          </button>
        </div>
      </div>

      <!-- 展开状态下的原始布局 -->
      <div v-else>
        <div class="sidebar-header">
          <div class="sidebar-actions">
            <button @click="toggleCollapse" class="collapse-btn" title="收起侧边栏">
              <Icon icon="mdi:chevron-left-box-outline" width="26" height="26" />
            </button>
            <button @click="createNewConversation" class="new-chat-btn" title="新建会话">
              <Icon icon="mdi:content-save-edit" width="26" height="26" />
            </button>
          </div>
        </div>
        <div class="sidebar-content">
          <ChatSidebar :conversations="chatStore.conversations" :activeId="chatStore.activeConversationId"
            @select="selectConversation" @create="createNewConversation" @delete="deleteConversation" />
        </div>
      </div>
    </div>

    <!-- Main chat area -->
    <div class="main-content">
      <!-- Mobile header -->
      <div class="mobile-header">
        <button @click="toggleSidebar" class="toggle-btn">
          <span class="menu-icon">☰</span>
        </button>
        <h2 class="chat-title"> {{ appDetail.name || 'AI 助手' }} </h2>
      </div>
      <!-- 表单模式和聊天模式切换 - 使用 v-show 而不是 v-if 减少 hydration 不匹配 -->
      <div class="messages-container" :class="{ 'form-mode': isFormMode }" ref="messagesContainerRef">
        <!-- 客户端渲染 -->
        <ClientOnly>
          <div v-show="isFormMode && !isLoadingForm" class="form-mode-container">
            <WelcomeTip :welcome-tip="appDetail?.welcomeTip" :poster="appDetail?.poster" />

            <CustomerForm :appDetail="appDetail" :apiHeaders="apiHeaders" @form-submitted="handleFormSubmitted" />
          </div>
        </ClientOnly>

        <div v-show="!isFormMode || isLoadingForm">
          <WelcomeTip :welcome-tip="appDetail?.welcomeTip" :poster="appDetail?.poster" />

          <!-- 显示表单数据（如果有的话） -->
          <FormDataDisplay v-if="hasFormInputs" :form-config="appConfig" :inputs="currentConversationInputs" />
          <ChatMessages :messages="chatStore.currentMessages" :appDetail="appDetail" />
        </div>
      </div>

      <!-- Chat input area - 更改为悬浮样式 -->
      <div class="input-container-wrapper" v-show="!isFormMode || isLoadingForm">
        <div class="input-container">
          <ChatInput :apiHeaders="apiHeaders" :appDetail="appDetail" />
        </div>
      </div>


      <!-- 滚动到底部按钮 -->
      <div class="scroll-to-bottom-btn" @click="scrollToBottom">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
          stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <polyline points="6 9 12 15 18 9"></polyline>
        </svg>
      </div>


    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted, watch, computed } from 'vue'
  import { useChatStore } from '~/stores/chat'
  import ChatSidebar from '~/components/chat/ChatSidebar.vue'
  import ChatMessages from '~/components/chat/ChatMessages.vue'
  import ChatInput from '~/components/chat/ChatInput.vue'
  import CustomerForm from '~/components/chat/CustomerForm.vue'
  import WelcomeTip from '~/components/chat/WelcomeTip.vue'
  import FormDataDisplay from '~/components/chat/FormDataDisplay.vue'
  import { Icon } from '@iconify/vue'

  import { getV1Conversations, postDifyChatAppDetail } from '../../../service/yapi'
  const { signIn, token, data: userInfo, status, lastRefreshedAt, signOut, getSession } = useAuth()

  const chatStore = useChatStore()
  const route = useRoute()
  const showSidebar = ref(true)
  const sidebarCollapsed = ref(false) // 默认折叠状态


  // 添加对messages-container的引用
  const messagesContainerRef = ref(null)


  // 滚动到底部函数
  const scrollToBottom = () => {
    if (messagesContainerRef.value) {
      nextTick(() => {
        messagesContainerRef.value.scrollTop = messagesContainerRef.value.scrollHeight
      })
    }
  }

  // 监听消息列表变化，自动滚动到底部
  watch(() => chatStore.currentMessages, (newMessages, oldMessages) => {
    // 检查是否为初始加载或有新消息添加
    const isInitialLoad = !oldMessages || oldMessages.length === 0
    const hasNewMessages = newMessages.length > oldMessages?.length

    // 检查最后一条消息是否正在流式传输
    const lastMessage = newMessages[newMessages.length - 1]
    const isLastMessageStreaming = lastMessage?.isStreaming

    // 检查是否应该自动滚动
    if (isInitialLoad || hasNewMessages || isLastMessageStreaming) {
      scrollToBottom()
    }
  }, { immediate: true, deep: true })


  // 折叠/展开侧边栏
  function toggleCollapse() {
    sidebarCollapsed.value = !sidebarCollapsed.value
  }

  // 聊天API配置
  const apiHeaders = computed(() => ({
    appId: route.params.id,
    appuserId: userInfo.value?.id,
    token: token.value.split(' ')[1] || '',
  }))

  // 服务端获取应用详情数据
  const { data: appDetailData, pending: isAppDetailLoading, error: appDetailError } = await useAsyncData(
    `app-detail-${route.params.id}`,
    async () => {
      try {
        // 使用 postDifyChatAppDetail 接口获取应用详情
        const response = await postDifyChatAppDetail({ id: route.params.id })
        if (response?.code === 1000) {
          return response.data || {}
        }
        throw new Error(response?.message || '无法加载应用详情')
      } catch (error) {
        console.error('加载应用详情失败:', error)
        return {}
      }
    },
    {
      server: true, // 确保在服务端渲染
      lazy: false,  // 立即加载数据
    }
  )

  const appDetail = computed(() => appDetailData.value || {
    cost: 1
  })

  const appConfig = computed(() => {
    if (appDetail.value?.appConfig) {
      try {
        let config
        if (typeof appDetail.value.appConfig === 'string') {
          config = JSON.parse(appDetail.value.appConfig || '{}')
        } else if (typeof appDetail.value.appConfig === 'object') {
          config = appDetail.value.appConfig
        } else {
          config = {}
        }
        return config
      } catch (error) {
        console.error('解析 appConfig 失败:', error)
        return {}
      }
    }
    return {}
  })

  // 服务端获取会话列表
  const { data: conversationsData, pending: isConversationsLoading, error: conversationsError } = await useAsyncData(
    `conversations-${route.params.id}-${userInfo.value?.id || 'guest'}`,
    async () => {
      // 如果没有用户ID，则不获取会话列表
      if (!userInfo.value?.id) return []

      try {
        // 使用 getV1Conversations 接口获取会话列表
        const response = await getV1Conversations({
          appId: route.params.id,
          appuserId: userInfo.value.id,
          platform: 'momoai'
        })

        if (response?.code === 1000 && Array.isArray(response.data)) {
          return response.data
        }
        return []
      } catch (error) {
        console.error('获取会话列表失败:', error)
        return []
      }
    },
    {
      server: true,
      lazy: false,
      // 监听用户ID变化，当用户ID变化时重新获取会话列表
      watch: [() => userInfo.value?.id],
      // 仅在有用户ID时才请求
      enabled: () => !!userInfo.value?.id,
    }
  )

  // 初始化会话
  watch(conversationsData, async (newConversations) => {
    if (newConversations && newConversations.length > 0) {
      await chatStore.setConversations(
        newConversations,
        route.params.id,
        userInfo.value?.id
      )
    } else if (userInfo.value?.id) {
      // 如果没有会话，创建一个新的
      chatStore.createNewConversation()
    }
  }, { immediate: true })

  // 当用户信息更新时
  watch(() => userInfo.value, async (newVal) => {
    if (newVal && newVal.id && route.params?.id && !chatStore.activeConversationId) {
      // 可以在客户端重新获取会话
      await getAppConversations()
    }
  }, {
    deep: true
  })

  // 获取会话列表 (客户端备用方法)
  async function getAppConversations() {
    if (route.params?.id && userInfo.value?.id) {
      try {
        let appId = route.params?.id;
        let appuserId = userInfo.value.id;
        const res = await getV1Conversations({
          appId,
          appuserId,
          platform: 'momoai'
        });
        if (res.code == 1000 && Array.isArray(res.data)) {
          // 设置会话列表并自动选择第一个会话（内部会加载会话消息）
          await chatStore.setConversations(res.data, appId, appuserId);
        } else {
          console.error('获取会话数据格式错误:', res);
          // 如果获取会话失败但返回成功，创建一个新的临时会话
          if (res.code == 1000 && !chatStore.activeConversationId) {
            chatStore.createNewConversation();
          }
        }
      } catch (error) {
        console.error('获取会话失败:', error);
        // 如果出现错误且没有活跃会话，创建新的临时会话
        if (!chatStore.activeConversationId) {
          chatStore.createNewConversation();
        }
      }
    }
  }



  // 加载应用详情 (客户端备用方法)
  async function loadAppDetail() {
    try {
      if (route.params?.id) {
        const res = await postDifyChatAppDetail({ id: route.params.id });
        if (res.code === 1000) {
          return res.data || {};
        } else {
          console.error('获取应用详情失败:', res);
          return {};
        }
      }
    } catch (error) {
      console.error('获取应用详情出错:', error);
      return {};
    }
  }

  // 选择会话
  async function selectConversation(id) {
    let appId = route.params?.id;
    let appuserId = userInfo.value.id;
    await chatStore.selectConversation(id, true, appId, appuserId)
    if (window.innerWidth < 768) {
      showSidebar.value = false
    }
  }

  // 创建新会话
  function createNewConversation() {
    chatStore.createNewConversation()
    if (window.innerWidth < 768) {
      showSidebar.value = false
    }
  }

  // 删除会话
  function deleteConversation(id) {
    let appId = route.params?.id;
    let appuserId = userInfo.value.id;
    chatStore.deleteConversation(id, appId, appuserId)
  }

  // 清空当前会话
  function clearCurrentConversation() {
    chatStore.clearCurrentConversation()
  }

  // 表单模式相关
  const formFields = ref([])
  const isLoadingForm = ref(true) // 添加表单加载状态标记

  // 监听appConfig变化，检测是否有表单配置
  watch(() => appDetail.value?.appConfig, (newConfig) => {
    isLoadingForm.value = true // 开始解析前标记为加载状态

    try {
      if (!newConfig) {
        formFields.value = []
        isLoadingForm.value = false
        return
      }

      let config
      if (typeof newConfig === 'string') {
        config = JSON.parse(newConfig || '{}')
      } else if (typeof newConfig === 'object') {
        config = newConfig
      } else {
        config = {}
      }

      if (config && config.form && Array.isArray(config.form.fields)) {
        formFields.value = config.form.fields
      } else {
        formFields.value = []
      }
    } catch (error) {
      console.error('解析 appConfig 失败:', error)
      formFields.value = []
    } finally {
      isLoadingForm.value = false // 无论成功或失败，解析完成后都更新状态
    }
  }, { immediate: true, deep: true })

  // 获取当前会话的inputs数据
  const currentConversationInputs = computed(() => {
    const activeId = chatStore.activeConversationId;
    if (!activeId || !chatStore.conversations[activeId]) return {};

    return chatStore.conversations[activeId].inputs || {};
  });

  // 判断当前会话是否有表单输入
  const hasFormInputs = computed(() => {
    return Object.keys(currentConversationInputs.value).length > 0;
  });

  // 计算是否是表单模式 - 修复 SSR 兼容性问题
  const isFormMode = computed(() => {


    // 必要的安全检查
    if (!chatStore || !chatStore.conversations) {
      return false;
    }

    // 如果没有表单字段，则不是表单模式
    if (!formFields.value || formFields.value.length === 0) {
      return false;
    }

    // 检查当前会话
    const activeId = chatStore.activeConversationId;
    if (!activeId || !chatStore.conversations[activeId]) {
      return false;
    }

    // 如果当前会话有表单输入，则不是表单模式
    if (Object.keys(currentConversationInputs.value).length > 0) {
      return false;
    }

    // 如果当前会话没有消息，则是表单模式
    return chatStore.currentMessages.length === 0;
  });

  // 客户端挂载后重新计算表单模式状态
  onMounted(async () => {
    if (appDetail.value?.name) {
      document.title = appDetail.value.name || 'AI 助手'
    }

    // 响应式调整侧边栏
    const handleResize = () => {
      if (window.innerWidth >= 768) {
        showSidebar.value = true
        // 默认折叠状态保持不变
      } else {
        showSidebar.value = false
        sidebarCollapsed.value = false // 在移动端不折叠，使用全屏模式
      }
    }

    window.addEventListener('resize', handleResize)
    handleResize() // 初始调用一次

    // 客户端挂载后，确保当前会话的消息已加载
    if (process.client && chatStore.activeConversationId) {
      const activeId = chatStore.activeConversationId;
      // 如果是真实会话ID且没有消息，则加载消息
      if (!activeId.startsWith('temp_') && chatStore.currentMessages.length === 0) {
        console.log('客户端挂载后加载会话消息:', activeId);
        let appId = route.params?.id;
        let appuserId = userInfo.value?.id;
        if (appId && appuserId) {
          await chatStore.loadConversationMessages(activeId, '', appId, appuserId);
        }
      }

      // 在表单加载完成后重新评估表单模式状态
      isLoadingForm.value = false;
      scrollToBottom()

    }

    return () => {
      window.removeEventListener('resize', handleResize)
    }
  })

  // 处理表单提交完成
  const handleFormSubmitted = () => {
    // 表单提交后刷新会话内容，确保切换到聊天模式
    console.log("表单已提交，切换到聊天模式")
  }

  // 切换侧边栏显示/隐藏
  function toggleSidebar() {
    showSidebar.value = !showSidebar.value
  }

  // 页面加载时初始化
  onMounted(() => {
    if (appDetail.value?.name) {
      document.title = appDetail.value.name || 'AI 助手'
    }

    // 响应式调整侧边栏
    const handleResize = () => {
      if (window.innerWidth >= 768) {
        showSidebar.value = true
        // 默认折叠状态保持不变
      } else {
        showSidebar.value = false
        sidebarCollapsed.value = false // 在移动端不折叠，使用全屏模式
      }
    }

    window.addEventListener('resize', handleResize)
    handleResize() // 初始调用一次

    return () => {
      window.removeEventListener('resize', handleResize)
    }
  })

  // 设置页面元数据，包括认证要求和SSR配置
  definePageMeta({
    auth: false,
    ssr: true
  });
</script>

<style lang="scss" scoped>
  .chat-container {
    display: flex;
    height: calc(100vh - 120px);
    width: 100%;
  }

  .sidebar {
    width: 260px;
    flex: 0 0 260px;

    background-color: #f7f7f7;
    transition: all 0.3s;
    z-index: 10;
    display: flex;
    flex-direction: column;

    &.hidden {
      margin-left: -300px;
    }

    &.collapsed {
      width: 80px;
      flex: 0 0 80px;
      overflow: hidden;
    }

    // 折叠状态下的垂直布局
    .collapsed-layout {
      display: flex;
      flex-direction: column;
      align-items: center;
      height: 100%;
      padding: 15px 0;
    }

    .collapsed-item {
      margin-bottom: 25px;
      display: flex;
      justify-content: center;
      width: 100%;


      &.logo-container {
        margin-bottom: 30px;

        .sidebar-logo {
          height: 40px;
          width: auto;
        }
      }
    }

    // 统一的按钮样式
    .sidebar-action-btn {
      width: 48px;
      height: 48px;
      border-radius: 50%;
      background-color: #f0f0f0;
      border: none;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: all 0.2s;

      &:hover {
        background-color: #e0e0e0;
      }

      .icon {
        font-size: 18px;
        line-height: 1;
      }
    }

    // 展开状态下的样式
    .sidebar-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;

      .sidebar-actions {
        display: flex;
        width: 100%;
        justify-content: space-between;

        .collapse-btn,
        .new-chat-btn {
          background: none;
          border: none;
          cursor: pointer;
          padding: 5px;
          border-radius: 4px;
          display: flex;

          align-items: center;
          justify-content: center;
          color: #666;

          &:hover {
            background-color: #e0e0e0;
          }
        }

        .collapse-icon {
          font-size: 20px;
        }

        .new-chat-btn {
          font-size: 20px;
          font-weight: bold;
        }
      }
    }

    .sidebar-content {
      flex-grow: 1;
      overflow: auto;
    }
  }

  .main-content {
    display: flex;
    flex-direction: column;
    flex-grow: 1;
    box-sizing: border-box;
    position: relative;

    /* 为固定定位输入框提供相对定位 */
    .scroll-to-bottom-btn {
      position: fixed;
      bottom: 200px;
      right: 50px;
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background-color: #35c6f4;
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
      z-index: 10;
      transition: all 0.2s;

      &:hover {
        background-color: #40a9ff;
      }
    }
  }

  .mobile-header {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid #e6e6e6;
    background-color: #fff;

    .toggle-btn {
      background: none;
      border: none;
      font-size: 20px;
      cursor: pointer;
      padding: 4px 8px;
      margin-right: 12px;
    }

    .chat-title {
      flex-grow: 1;
      font-size: 18px;
      font-weight: 500;
      margin: 0;
    }

    .header-actions {
      display: flex;

      .action-btn {
        background: none;
        border: none;
        font-size: 18px;
        cursor: pointer;
        padding: 4px 8px;
        margin-left: 8px;
        border-radius: 4px;

        &:hover {
          background-color: #f0f0f0;
        }
      }
    }
  }

  .messages-container {
    flex-grow: 1;
    overflow-y: scroll;
    overflow-x: hidden;
    position: relative;
    padding-bottom: 120px;
    /* 为输入框腾出空间 */

    &.form-mode {
      display: flex;
      flex-direction: column;
      padding-bottom: 0;
    }

    .form-mode-container {
      height: 100%;
      overflow-y: auto;
      padding: 20px;
      display: flex;
      flex-direction: column;
    }
  }

  /* 悬浮输入框容器 */
  .input-container-wrapper {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    justify-content: center;

  }

  .input-container {
    width: 100%;

    background-color: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(8px);
    border-radius: 10px;
    box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
  }

  @media (min-width: 768px) {
    .mobile-header {
      padding: 16px 24px;

      .toggle-btn {
        display: none;
      }
    }

    .input-container {
      margin: 0 auto;
    }
  }

  @media (max-width: 767px) {
    .sidebar {
      position: fixed;
      top: 0;
      left: 0;
      height: 100%;
      width: 100%;
      max-width: 320px;
      z-index: 100;
      box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
    }


  }
</style>